import React from 'react';
import { inject, observer} from 'mobx-react';
import {WeaTableNew,WeaLogView,WeaSwitch} from 'comsMobx';
import { Button } from 'antd';
import * as mobx from 'mobx';
import {WeaTop,WeaTab,WeaLeftRightLayout,WeaRightMenu,WeaPopoverHrm,WeaTools,WeaErrorPage,WeaLocaleProvider,WeaFormItem,WeaSearchGroup} from 'ecCom';

import stores from '../../stores';
import AddTemplate from './Add';
import EditTemplate from './Edit';
import AddshareTemplate from './AddShare';
import ModelSet from './modelSet';

const WeaLogViewComp = WeaLogView.Component;
const { toJS } = mobx;
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
const Base64 = WeaTools.Base64;

@inject('wfFreeFlowTemplateStore')

@observer
class ListMine extends React.Component {
    constructor(props) {
        super(props);
        this.doInitTitle(this.props);
    }

    varTemp = {
      logParams:{params: {}},
      btns: [],
      rightBtns: [],
      advanceBtns: [],
      searchType: ['base','advanced']
    }
    doInitTitle(props){
        const { wfFreeFlowTemplateStore,location } = props;
        const  tabTitle  = location.query.tabTitle || "";
        wfFreeFlowTemplateStore.title = getLabel(504067,'流转模板');
        if(tabTitle !="" && tabTitle !=undefined){
            wfFreeFlowTemplateStore.title = Base64.decode(decodeURIComponent(location.query.tabTitle));
        }
    }
    doInit(props){
        const { wfFreeFlowTemplateStore } = props;
        const{ location } = this.props;
        if(location.query.tabTitle){
            wfFreeFlowTemplateStore.title = Base64.decode(decodeURIComponent(location.query.tabTitle));
        }
        const { searchList , getAddTemplateBaseData,clearListFormFields} = wfFreeFlowTemplateStore;
        getAddTemplateBaseData();
        clearListFormFields();
        searchList();
    }
    componentDidMount() {
        this.doInit(this.props);
    }
    componentWillReceiveProps(nextProps) {
        if(this.props.location.key !== nextProps.location.key) {
            const { wfFreeFlowTemplateStore } = this.props;
            wfFreeFlowTemplateStore.clearStatus();
            this.doInit(nextProps);
        }
    }

    componentWillUnmount() {
        const { wfFreeFlowTemplateStore } = this.props;
        wfFreeFlowTemplateStore.clearStatus();
    }
    setShowSearchAd=bool=>{this.props.wfFreeFlowTemplateStore.setShowSearchAd(bool)};
    hideSearchAd=()=> this.props.wfFreeFlowTemplateStore.setShowSearchAd(false);
    onSearch= v=>this.props.wfFreeFlowTemplateStore.searchList();
    onSearchChange= v=>{this.props.wfFreeFlowTemplateStore.appendListFormFields({name:{value:v}})}
    render() {
        const { wfFreeFlowTemplateStore } = this.props;
        const { title, loading , tableStore , setShowSearchAd , showSearchAd , appendListFormFields , listForm , searchList,
            logModalShow,setLogModalShow,logStore,logArray} = wfFreeFlowTemplateStore;
        const listFormParams = listForm.getFormParams();
        const loadingTable = tableStore.loading;
        this.varTemp.logParams.params = JSON.stringify(logArray);
        this.varTemp.btns = this.varTemp.rightBtns =  this.varTemp.advanveBtns = [];
        this.varTemp.btns =  this.getTopButtons();
        this.varTemp.rightBtns = this.getRightMenu();
        this.varTemp.advanceBtns = this.getListAdButtons();
        return (
            <div className="wf-free-flowset-template">
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@dwsf68`}
              collectParams={{favname:getLabel(504067,'流转模板'), favouritetype:2}}
              datas={this.varTemp.rightBtns}
              >
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@ernzwg`}
                  title={title}
                  loading={ loading || loadingTable}
                  icon={<i className='icon-coms-workflow' />}
                  iconBgcolor='#0079DE'
                  buttons={this.varTemp.btns}
                  buttonSpace={10}
                  showDropIcon={true}
                  dropMenuDatas={this.varTemp.rightBtns}
                >
                  <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@p5hc6i`}
                    buttonsAd={this.varTemp.advanceBtns}
                    searchType={this.varTemp.searchType}
                    advanceHeight = {75}
                    searchsBaseValue={listFormParams.name}
                    setShowSearchAd={this.setShowSearchAd}
                    hideSearchAd={this.hideSearchAd}
                    searchsAd={this.getCusAdvancedSearch()}
                    showSearchAd={showSearchAd}
                    onSearch={this.onSearch}
                    onSearchChange={this.onSearchChange}
                  />
                  <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@y6ti95`}
                    comsWeaTableStore={tableStore}
                    hasOrder={true}
                    needScroll={true}
                  />
              </WeaTop>
        </WeaRightMenu>
        <AddTemplate ecId={`${this && this.props && this.props.ecId || ''}_AddTemplate@vnb8zn`}/>
        <EditTemplate ecId={`${this && this.props && this.props.ecId || ''}_EditTemplate@g7j7gm`}/>
        <AddshareTemplate ecId={`${this && this.props && this.props.ecId || ''}_AddshareTemplate@o7rn2e`}/>
        <ModelSet ecId={`${this && this.props && this.props.ecId || ''}_ModelSet@1cyb64`}/>
        <WeaLogViewComp ecId={`${this && this.props && this.props.ecId || ''}_WeaLogViewComp@j14zwm`} visible={logModalShow} onCancel={this.cancel} logStore={logStore} params={this.varTemp.logParams}/>
      </div>
    )
    }
    cancel = ()=> this.props.wfFreeFlowTemplateStore.setLogModalShow(false);
    getAdvancedSearch(){
        const { wfFreeFlowTemplateStore } = this.props;
        const { listForm , listCondition} = wfFreeFlowTemplateStore;
        const coms = listForm.render({
                needTigger: false,
                showGroup:true,
                showTitle:false,
            }, {}
        );
        return coms;
    }
    getCusAdvancedSearch() {
        const { wfFreeFlowTemplateStore } = this.props;
        const { listForm, listCondition,searchList,setShowSearchAd } = wfFreeFlowTemplateStore;
        const {isFormInit} = listForm;
        let group = [];
        isFormInit && toJS(listCondition).map((c,index) =>{
            let items = [];
            c.items.map(field => {
                let col = 2;
                if (field.conditionType.toUpperCase() == WeaTools.types.CASCADER) col = 1;
                items.push({
                    com:(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@jcbceu@${field.domkey[0]}`}
                    label={`${field.label}`}
                labelCol={{span: `${field.labelcol}`}}
                ratio1to2
                error={listForm.getError(field)}
                tipPosition="bottom"
                wrapperCol={{span: `${field.fieldcol}`}}>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@gf4ue6@${field.domkey[0]}`} fieldConfig={field} form={listForm} onEnterSearch={this.onEnterSearch}/>
                </WeaFormItem>),
                col:col,
                    hide: listForm.isHide(field, (keys, allParams)=> {
                    // console.log(keys, allParams);
                    return false;
                })
            })
            });
            group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@i9wmso@${index}`} needTigger={false} showTitle = {false} showGroup={true} items={items}/>)
        });
        return group;
    }
    onEnterSearch = ()=>{
      const { wfFreeFlowTemplateStore } = this.props;
      const { searchList,setShowSearchAd } = wfFreeFlowTemplateStore;
      searchList();
      setShowSearchAd(false);
    }
    addTemplate(){
        const { wfFreeFlowTemplateStore } = this.props;
        const { setAddModalShow } = wfFreeFlowTemplateStore;
        setAddModalShow(true);
    }
    batchDelete(){
        const { wfFreeFlowTemplateStore } = this.props;
        const { deleteTemplateItem , tableStore} = wfFreeFlowTemplateStore;
        const selectedRowKeys = tableStore.selectedRowKeys;
        deleteTemplateItem(selectedRowKeys.join(','),true);
    }
    getTopButtons(){
        const { wfFreeFlowTemplateStore } = this.props;
        const { tableStore } = wfFreeFlowTemplateStore;
        const selectedRowKeys = tableStore.selectedRowKeys;
        let btns = [];
        btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yl7ado@addTemplate`} type="primary" onClick={()=>{this.addTemplate()}}>{getLabel(365,'新建')}</Button>);
        btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@p8ss62@batchDelete`} type="primary" disabled={selectedRowKeys.length <= 0} onClick={()=>this.batchDelete()}>{getLabel(386728,'批量删除')}</Button>);
        return btns;
    }
    getListAdButtons(){
        const { wfFreeFlowTemplateStore } = this.props;
        const {searchList,setShowSearchAd,clearListFormFields} = wfFreeFlowTemplateStore;
        return [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kb6gjf@search`} type="primary" onClick={()=>{searchList();setShowSearchAd(false);}}>{getLabel(197,'搜索')}</Button>),
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fob167@reset`} type="ghost" onClick={()=>{clearListFormFields();}}>{getLabel(2022,'重置')}</Button>),
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yrvuy3@cancel`} type="ghost" onClick={()=>{setShowSearchAd(false)}}>{getLabel(31129,'取消')}</Button>)
    ];
    }
    getRightMenu(){
        const { wfFreeFlowTemplateStore } = this.props;
        const { tableStore , setModelSetModalShow,setLogModalShow} = wfFreeFlowTemplateStore;
        const selectedRowKeys = tableStore.selectedRowKeys;
        let rtMenus = [];
        rtMenus.push({
            key: "add",
            icon: <i className="icon-coms-Add-to-o"/>,
            content:getLabel(365,'新建'),
            onClick: key =>{
            this.addTemplate();
        }
    });
        rtMenus.push({
            key: "batchdelete",
            icon: <i className='icon-coms-Batch-delete'/>,
            content:getLabel(386728,'批量删除'),
            disabled:selectedRowKeys.length <= 0,
            onClick: key =>{
            this.batchDelete();
        }
    });
        rtMenus.push({
            key:"colSet",
            icon: <i className='icon-coms-Custom'/>,
            content:getLabel(32535,'显示列定制'),
            onClick: key =>{
            tableStore.setColSetVisible(true);
            tableStore.tableColSet(true);
        }
    });
        // rtMenus.push({
        //     key: "log",
        //     icon: <i className='icon-coms-Print-log'/>,
        //     content:getLabel(83,'日志'),
        //     onClick: key =>{
        //         setLogModalShow(true);
        //     }
        // });
        return rtMenus;
    }
}

export default WeaTools.tryCatch(React,
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@0ilqw2`} msg={ props.error ? props.error : getLabel(383324,' 对不起，该页面异常，请联系管理员 ')+'！'} />,
{error: ""}
)(ListMine);

window.freeFlowTemplateUtils = (function(){
    return {
        editTemplate(id){//编辑模板
            const wfFreeFlowTemplateStore= stores['wfFreeFlowTemplateStore'];
            const { setEditModalShow , tableStore , setCurrentModalInfo} = wfFreeFlowTemplateStore;
            wfFreeFlowTemplateStore.curTemplateId = id;
            const datas = tableStore.datas;
            const curItem = datas.filter((v)=>v.id == id);
            setCurrentModalInfo({
                name:curItem[0].name,namespan:curItem[0].namespan,
                type:curItem[0].type,typespan:curItem[0].typespan
            });
            setEditModalShow(true,curItem);
        },
        modelSet(id){//模板设置
            const wfFreeFlowTemplateStore= stores['wfFreeFlowTemplateStore'];
            const { setModelSetModalShow , setCurrentModalInfo , tableStore} = wfFreeFlowTemplateStore;
            wfFreeFlowTemplateStore.curTemplateId = id;
            const datas = tableStore.datas;
            const curItem = datas.filter((v)=>v.id == id);
            setCurrentModalInfo({
                name:curItem[0].name,namespan:curItem[0].namespan,
                type:curItem[0].type,typespan:curItem[0].typespan
            });
            setModelSetModalShow(true);
        },
        shareRange(id){//共享范围
            const wfFreeFlowTemplateStore= stores['wfFreeFlowTemplateStore'];
            const { setEditModalShow , tableStore , addForm , getShareRangeList} = wfFreeFlowTemplateStore;
            wfFreeFlowTemplateStore.curTemplateId = id;
            wfFreeFlowTemplateStore.editSelectedTabKey = '1';
            const datas = tableStore.datas;
            const curItem = datas.filter((v)=>v.id == id);
            setEditModalShow(true,curItem);
            addForm.updateFields({type:{value:'1'}},false);
            getShareRangeList();
        },
        deleteTemplate(id){//删除模板
            const wfFreeFlowTemplateStore= stores['wfFreeFlowTemplateStore'];
            const { deleteTemplateItem } = wfFreeFlowTemplateStore;
            deleteTemplateItem(id);
        },
        log(){//日志
            const wfFreeFlowTemplateStore= stores['wfFreeFlowTemplateStore'];
            const { setLogModalShow } = wfFreeFlowTemplateStore;
            setLogModalShow(true);
        },
        deleteShare(id){//共享范围删除
            const wfFreeFlowTemplateStore= stores['wfFreeFlowTemplateStore'];
            const { deleteShareItem } = wfFreeFlowTemplateStore;
            deleteShareItem(id);
        }
    }
})();